#!/bin/bash
cd `dirname $0`

#cat $1>$2.pids
chmod +x ./treeps.sh
./treeps.sh $1 $2.pids

netstat -nltp > $2.port

ps -ex -o %p, -o %P,  -o %C, -o %mem, -o ,%a  >$2.ex
#   PID,  PPID,%CPU,%MEM,COMMAND


let totalmem=0
rm -f $2
cat $2.pids | while  read pid 
do
  if [ ! -z $pid ] 
  then
       cpid=`grep -P "^\s*$pid," $2.ex`
       #echo $cpid
       #if [ ! -z $cpid ] 
       #then 
         echo [ProcessId=$pid] >>$2
	     echo ParentProcessId=`echo $cpid | grep -Po "^\s*$pid,\s*\K\d+"` >>$2
	     echo CPU=            `echo $cpid | grep -Po "^\s*$pid,\s*\d+,\s*\K\d+(\.\d+)+"`% >>$2
	     WorkingSetSize=`echo $cpid | grep -Po "^\s*$pid,\s*\d+,\s*\d+(\.\d+)?,\s*\K\d+(\.\d+)?"`
	     totalmem=`echo $totalmem+$WorkingSetSize | bc`
	     if [ "${totalmem:0:1}" == "." ]
	     then
	        echo memory=0${totalmem}% >$2.mem
	     else
	        echo memory=${totalmem}% >$2.mem
	     fi
         if [ "${WorkingSetSize:0:1}" == "." ]
         then
            echo WorkingSetSize= 0${WorkingSetSize}% >>$2
         else
            echo WorkingSetSize= ${WorkingSetSize}% >>$2
         fi
         echo port=`cat $2.port | grep -P "\s${pid}/" | grep -Po "[0-9\.:a-f]+:\d+\s"`  >>$2
         echo CommandLine=    `echo $cpid | grep -Po "^\s*$pid,\s*\d+,\s*\d+(\.\d+)?,\s*\d+(\.\d+)?,\K.*"` >>$2
       #fi
  fi
done

if [  -e $2.mem ]
then
    echo [total] >>$2
    cat $2.mem >>$2
fi
rm -f $2.*





